<template>
  <div ref="container">
    <div class="coupon-list" v-if="couponsList.length > 0">
      <div class="tips">
        <p class="title">优惠劵使用说明：</p>
        <p class="tip_content">
          1、同一个商品仅可使用一张平台优惠劵，不可叠加使用多张优惠劵。
        </p>
        <p class="tip_content">
          2、如商品可用优惠劵存在多张时，系统默认核销优惠劵金额最高的优惠劵。
        </p>
        <p class="tip_content">3、每张优惠劵用户当日只可领取一次。</p>
      </div>
      <div
        class="item bg2 acea-row"
        :class="{
          bg1: item.type == 1
        }"
        v-for="(item, index) in couponsList"
        :key="index"
      >
        <div class="money" :class="item.status == 1 ? 'moneyGray' : ''">
          <div>
            ￥<span class="num">{{ item.coupon_price }}</span>
          </div>
          <div class="pic-num">满{{ item.use_min_price }}元可用</div>
          <div class="pic-num">{{ formatDec(item.dec) }}</div>
          <div
            class="dec_info"
            v-if="item.dec.length > 7"
            @click="item.showInfo = !item.showInfo"
          >
            详细信息
          </div>
          <CouponDecWindow :decInfo="item.showInfo" :detail="item.dec" />
        </div>
        <div class="text">
          <div class="condition">
            <span class="line-title">{{ item.title }}</span>
          </div>
          <div class="coupon_time">
            <div>
              <span v-if="item.time_type == 1">{{ item.time }}</span>
              <span v-else>领取后{{ item.time }}天有效</span>
            </div>
          </div>
          <div
            class="data acea-row row-between-wrapper"
            v-if="item.limit_type == 0"
          >
            <div class="bnt" v-if="item.status == 1" @click="toUse(item)">
              立即使用
            </div>
            <div class="bnt gray" v-else-if="item.status == 2">已使用</div>
            <div class="bnt gray" v-else-if="item.status == 3">已过期</div>
            <div class="bnt" v-else @click="getType(item)">
              领取
            </div>
          </div>
          <div class="data acea-row row-between-wrapper" v-else>
            <div class="bnt" v-show="!item.receive" @click="getType(item)">
              领取
            </div>
            <div class="bnt" v-show="item.receive" @click="toUse(item)">
              立即使用
            </div>
          </div>
        </div>
      </div>
    </div>
    <Loading :loaded="loadend" :loading="loading"></Loading>
    <!--暂无优惠券-->
    <div class="no_coupons" v-cloak v-if="couponsList.length === 0">
      <div class="noPictrue">
        <img src="@assets/images/coupon/no_data.png" class="image" />
      </div>
      <p class="noText">一大波优惠劵即将来袭</p>
    </div>
  </div>
</template>
<script>
import { getCoupon, getCouponReceive, getCouponsWithPhone } from "@api/user";
import Loading from "@components/Loading";
import CouponDecWindow from "@components/couponDecWindow";
import shareMsg from "../../../assets/js/common/shareConfig.js";
export default {
  name: "getCoupon",
  components: {
    Loading,
    CouponDecWindow
  },
  props: {},
  data: function() {
    return {
      page: 1,
      limit: 10,
      couponsList: [],
      loading: false,
      loadend: false
    };
  },
  mounted: function() {
    let that = this;
    if (this.$route.query.from1 == "app") {
      shareMsg.shareConfig("app", "0", "0", "", "", "", "", "", "0");
      this.getParameter();
      window["onWebResponse"] = str => {
        that.onWebResponse(str);
      };
    } else {
      this.getUseCoupons();
    }
  },
  methods: {
    formatDec(text) {
      return text.length > 7 ? `${text.slice(0, 7)}...可用` : text;
    },
    // 获取app登录状态
    onWebResponse: function(str) {
      var obj = JSON.parse(str);
      var action = obj.action;
      var content = obj.content;
      if (action == "setUserInfo") {
        let isToken = content.ds_token;
        // let expires_time = content.ds_expires_time;
        // let isSalt = content.salt;
        this.$store.commit("LOGIN", isToken);
        this.$nextTick(() => {
          setTimeout(() => {
            this.getUseCoupons();
          }, 0);
        });
      }
    },
    getParameter: function() {
      var self = this;
      var u = navigator.userAgent,
        app = navigator.appVersion;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      const win = window;
      var obj = {
        action: "getParameter",
        content: {
          method: "setUserInfo",
          Parameter: {}
        }
      };
      if (isAndroid) {
        App.onAppResponse(JSON.stringify(obj));
      }
      if (isIOS) {
        win.webkit.messageHandlers.onAppResponse.postMessage(
          JSON.stringify(obj)
        );
      }
    },
    // 使用优惠劵
    toUse(coupon) {
      let { url_type, url_text } = coupon;
      let { from1 } = this.$route.query;
      if (from1 != "app") {
        url_text = url_text.replace("from1=app", "");
      }
      if (url_type == 0) {
        this.$router.push(`/detail/${url_text}`);
      } else {
        window.location.href = url_text;
      }
    },
    // 登录用户领取
    getCoupon: function(coupon) {
      let that = this;
      const { id } = coupon;
      getCouponReceive([id])
        .then(() => {
          // this.getUseCoupons();
          that.$dialog.toast({ mes: "领取成功" });
          coupon.receive = true;
          coupon.status = 1;
        })
        .catch(function(res) {
          that.$dialog.toast({ mes: res.msg });
        });
    },
    // 优惠劵列表
    getUseCoupons: function() {
      let that = this;
      let q = {
        page: 0
      };
      getCoupon(q).then(res => {
        that.loading = false;
        //apply();js将一个数组插入另一个数组;
        this.couponsList = res.data.map(item => {
          return {
            ...item,
            showInfo: false,
            receive: false
          };
        });
        that.loadend = res.data.length < that.limit; //判断所有数据是否加载完成；
      });
    },
    // 手机号领取
    getCouponsWithPhone(coupon) {
      const params = {
        phone: this.$route.query.phone,
        sign: coupon.id
      };
      getCouponsWithPhone(params)
        .then(() => {
          this.$dialog.toast({ mes: "领取成功" });
          coupon.receive = true;
          coupon.status = 1;
        })
        .catch(err => {
          this.$dialog.toast({ mes: err.msg });
        });
    },
    // 领取类型
    getType(coupon) {
      let phone = this.$route.query.phone;
      if (phone) {
        this.getCouponsWithPhone(coupon);
      } else {
        this.getCoupon(coupon);
      }
    }
  }
};
</script>
<style scoped>
.bg-color-check {
  color: #e83323;
  background: #fff7f7;
  border: 1px solid #e83323;
}
</style>
